package com.ego.cart.service.impl;

import com.ego.cart.service.CartService;
import com.ego.commons.constant.Constant;
import com.ego.commons.pojo.CartPojo;
import com.ego.commons.pojo.EgoResult;
import com.ego.commons.pojo.ShopCart;
import com.ego.commons.utils.CookieUtils;
import com.ego.commons.utils.JsonUtils;
import com.ego.commons.utils.ServletUtil;
import com.ego.dubbo.service.TBItemDubboService;
import com.ego.pojo.TbItem;
import com.ego.pojo.TbItemDetail;
import com.ego.pojo.TbUser;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.Servlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

@Service
public class CartServiceImpl implements CartService {

    @Autowired
    private RedisTemplate redisTemplate;

    @DubboReference
    private TBItemDubboService tbItemDubboService;

    @Value("${ego.item.detailRedisKey}")
    private String redisDetialKey;

    @Override
    public void cartAdd(Long id, int num) {
        //从Redis中获取缓存的商品详情数据
        TbItemDetail tbItemDetail = (TbItemDetail) redisTemplate.opsForValue().get(redisDetialKey + id);

        //1.创建购物车对象 CartPojo 封装数据
        CartPojo cartPojo = new CartPojo();
        //将TbItemDetail设置给CartPojo
        BeanUtils.copyProperties(tbItemDetail, cartPojo);
        //如果上面拷贝num是商品库存数量，需要重新设置CartPojo的num为用户购买的数量
        cartPojo.setNum(num);


        //获取购物车
        ShopCart shopCart = this.getShopCart();

        //添加数据到购物车
        shopCart.addToCart(cartPojo);

        //存储购物车
        this.saveCartToCookieOrRedis(shopCart);
    }


    @Override
    public List<CartPojo> cartList() {


        //获取购物车
        ShopCart shopCart = this.getShopCart();


        return shopCart.getCartList();
    }

    @Override
    public EgoResult updateCartItemNum(Long id, int num) {
        try {

            //获取购物车
            ShopCart shopCart = this.getShopCart();

            //更改购物车数据
            shopCart.updateToCart(id, num);

            //保存购物车
            this.saveCartToCookieOrRedis(shopCart);


            return EgoResult.ok();
        } catch (Exception e) {
            e.printStackTrace();
            return EgoResult.error("修改购物车数据失败");
        }
    }

    @Override
    public EgoResult deleteCartItemByItemId(Long id) {

        try {

            //获取购物车
            ShopCart shopCart = this.getShopCart();

            //删除购物车数据
            shopCart.deleteToCart(id);

            //保存购物车
            this.saveCartToCookieOrRedis(shopCart);


            return EgoResult.ok();
        } catch (Exception e) {
            e.printStackTrace();
            return EgoResult.error("删除购物车数据失败");
        }

    }

    @Override
    public List<CartPojo> orderCartByIds(List<Long> ids) {

        //获取购物车数据
        ShopCart shopCart = this.getShopCart();

        //存放结算订单的商品
        List<CartPojo> orderList = new ArrayList<>();

        //获取购物车的商品数据
        List<CartPojo> cartList = shopCart.getCartList();

        for (CartPojo cartPojo : cartList) {
            //如果用户结算的商品id在购物车中有对应的商品对象，才会添加到结算集合中：orderList
            if (ids.contains(cartPojo.getId())) {


                //从数据库中查询出对应的商品
                TbItem tbItem = tbItemDubboService.selectById(cartPojo.getId());

                //获取商品详情库存数量
                Integer storageNum = tbItem.getNum();

                //获取购买数量
                Integer buyNum = cartPojo.getNum();

                //如果库存数量大于等于购买数量说明库存足够，可以购买
                if (storageNum >= buyNum) {
                    cartPojo.setEnough(true);
                }

                orderList.add(cartPojo);
            }
        }

        return orderList;
    }


    /**
     * 存储购物车，如果未登录：存储到Cookie，如果登录：存储到Redis
     *
     * @param shopCart
     */
    public void saveCartToCookieOrRedis(ShopCart shopCart) {

        HttpSession session = ServletUtil.getRequest().getSession();
        //获取登录用户的Session中的信息
        TbUser loginUser = (TbUser) session.getAttribute(Constant.LOGIN_USER_IN_SESSION);

        if (loginUser != null) {

            redisTemplate.opsForValue().set(Constant.LOGIN_USER_REDIS_SHOP_CART_KEY_PREFIX + loginUser.getUsername(), shopCart);
        } else {
            ShopCart.saveCartToCookie(shopCart);
        }

    }


    /**
     * 封装获取购物车数据
     *
     * @return
     */
    public ShopCart getShopCart() {

        HttpSession session = ServletUtil.getRequest().getSession();
        //获取登录用户的Session中的信息
        TbUser loginUser = (TbUser) session.getAttribute(Constant.LOGIN_USER_IN_SESSION);

        ShopCart shopCart = null;

        if (loginUser != null) {
            shopCart = (ShopCart) redisTemplate.opsForValue().get(Constant.LOGIN_USER_REDIS_SHOP_CART_KEY_PREFIX + loginUser.getUsername());
            if (shopCart == null) {
                shopCart = new ShopCart();
            }
        } else {
            //获取购物车
            shopCart = ShopCart.getShopCartByCookie();
        }
        return shopCart;
    }
}

